#include "boxnumbercontroller.h"
#include <QTextCodec>

extern QString boxNumber;//箱子编号

using namespace stefanfrings;

BoxNumberController::BoxNumberController(QObject* parent)
    : HttpRequestHandler(parent) {
    // empty
}

void BoxNumberController::service(HttpRequest &request, HttpResponse &response)
{
    //http://localhost:5001/Box_number https://slides.thearay.net http://localhost:5001
//    response.setHeader("Access-Control-Allow-Origin", "https://slides.thearay.net");//解决跨域问题
//    response.setHeader("Access-Control-Allow-Origin", "http://slides.thearay.net");//解决跨域问题
//    response.setHeader("Access-Control-Allow-Methods", "PUT,DELETE");//解决跨域问题

////    logger.info("method:"+request.getMethod());
//    response.setHeader("Access-Control-Allow-Credentials","true");
//    //告诉请求端，哪些自定义的头字段可以被允许添加
////    response.setHeader("Access-Control-Allow-Headers","X-Test-Cors");
//    //CORS请求预请求时不允许设置Content-Type，在预请求时告诉请求端可以
//    response.setHeader("Access-Control-Allow-Headers","content-type");
////    //允许跨域请求的最长时间,指定时间内不需要发送预请求过来。
////    response.setHeader("Access-Controller-Max-Age","1000");
//    response.setHeader("Access-Control-Allow-Headers","Access-Control-Request-Headers");

    QByteArray origin = request.getHeader("Origin");
    qDebug()<<__LINE__<<"origin="<<origin;
    response.setHeader("Access-Control-Allow-Origin", origin);//允许跨域源跨域访问
    response.setHeader("Access-Control-Allow-Headers", "appid,sign,Content-Type"); //允许跨域的header字段，根据需要自行添加删除
    response.setHeader("Access-Control-Allow-Credentials", "true");//允许携带cookie验证信息
    response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT");// 允许跨域的请求方法



    response.write(boxNumber.toUtf8(),true);
    QByteArray buf;
    buf=request.getMethod();
    qDebug()<<__LINE__<<"getMethod="<<buf;//POST GET 等访问方式
    buf=request.getPath();
    qDebug()<<__LINE__<<"getPath="<<buf;//http访问时追加路径
    buf=request.getVersion();
    qDebug()<<__LINE__<<"getVersion="<<buf;//HTTP版本("HTTP/1.1")
    buf=request.getBody();
    qDebug()<<__LINE__<<"getBody="<<buf;//传输过来的数据

    QByteArray urlDecode = QByteArray::fromPercentEncoding(buf);//URL解码
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");//指定QString的编码方式
    QString str = codec->toUnicode(urlDecode);//nameArray可以是char*，可以是QByteArray
    qDebug()<<__LINE__<<"接收到数据:"<<str;

    emit sendBoxfMain("0",str);
}
